from whiff import resolver
from whiff import whiffenv
from whiff.rdjson import jsonParse
from whiff.middleware import callTemplate

def erdDelete(env, start_response):
    env = resolver.process_cgi(env, parse_cgi=True)
    name = whiffenv.cgiGet(env, "name")
    rule = whiffenv.cgiGet(env, "Rule")
    rname = whiffenv.cgiGet(env, "rname")
    minimum = whiffenv.cgiGet(env, "minimum")
    maximum = whiffenv.cgiGet(env, "maximum")
    attributes = whiffenv.cgiGet(env, "attributes")
    attributes = attributes.split()
    required = whiffenv.cgiGet(env, "required")
    if required=="1":
        required = True
    else:
        required = False
    #pr "min/max", minimum, maximum
    if len(minimum)==1:
        minimum = int(minimum)
    if len(maximum)==1:
        maximum = int(maximum)
    #pr "key (name, rname,rule)", (name, rname,rule)
    rule = resolver.unquote(rule)
    name = name.strip()
    (flag, rulevalue, cursor) = jsonParse.parseValue(rule)
    if not flag:
        raise ValueError, "failed to parse rule "+repr(rule)
    if not name:
        raise ValueError, "no name found"
    #start_response('200 OK', [('Content-Type', 'application/javascript')])
    #yield "alert('trying to delete element %s');" % name
    #yield "alert('rule is %s');" % rule.replace("\n", " ")
    # remove all mentions of element
    newrule = list(rulevalue)
    newrule.append( ["foreign", name, attributes, rname, required, minimum, maximum] )
    env = env.copy()
    newrulestr = jsonParse.format(newrule)
    #pr "new rule is"
    #pr newrulestr
    resolver.override_cgi_require(env, "Rule", newrulestr)
    # deliver the javascript
    #pr "NOW CALLING SCHEMATEST"
    app = callTemplate.callTemplate("schemaTest.js")
    return app(env, start_response)

__wsgi__ = erdDelete
